package com.find.memories.photoviewer;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.find.memories.R;
import com.find.memories.gallery.PhotoItem;
import com.find.memories.photoviewer.CustomViewPager.ItemInfo;
import com.find.memories.util.Utils;

/**
 * CustomViewPagerAdapter를 확장하여 구현함.<br>
 * 이미지가 출력되는 화면과 관계된 기능은 대부분은 Adapter에 구현되어 있다.<br>
 * 명령은 Activity로 부터 전달 받는다.
 * @author Jang
 *
 */
public class PhotoViewerPagerAdapter extends CustomViewPagerAdapter {

	/**
	 * 주요 Body가 생성될 시 PhotoViewerActivity에 생성결과를 넘겨주기 위해 구현된 Listener
	 * @author Jang
	 *
	 */
	public interface AdapterPrimaryItemListener {
		public void createdPrimaryItem(int position);
	}
	
	private LayoutInflater mInflater;
	private PhotoViewerPager mPager;
	private FrameLayout mBody;
	private SlideStateListener mSlideStateListener = null;
	
	/**
	 * PhotoViewerActivity와 주소를 공유하는 ArrayList
	 */
	private ArrayList<PhotoItem> mPhotoList;
	
	/**
	 * 넘겨받은 데이터 사이즈만큼만 보여주기로 했으나 중간에 요청이 들어와서<br>
	 * 이미지 totalcount를 받고 없는 data는 직접 서버에서 받아오기로 변경
	 */
	private int mPhotoTotalCount = 0;
	private int mCurrentPosition = -1;
	private AdapterPrimaryItemListener mPrimaryListener = null;
	private Context mContext;
	private PhotoViewerBodyInterface mBodyInterface;
	
	public PhotoViewerPagerAdapter(Context context, LayoutInflater inflater) {
		super();
		mInflater = inflater;
		mContext = context;
	}

	@Override
	public int getCount() {
		return mPhotoTotalCount;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		// TODO Auto-generated method stub
		return view == ((FrameLayout) object);
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		// TODO Auto-generated method stub
		
		/**
		 * 호출되면 현재 생성된 Item이 있는지 check하고 있다면 생성된 item을 return 한다.
		 */
		PhotoViewerPager pager = (PhotoViewerPager) container;
		boolean isGifload = false;
		ArrayList<ItemInfo> list = pager.getPagerItemList();
		for (int i=0; i < list.size(); i++) {
			if (list.get(i).position == position) {
				return list.get(i).object;
			}
		}
		
		FrameLayout body = (FrameLayout) mInflater.inflate(R.layout.photo_viewer_body_thumbnail, null);

        final PhotoViewerThumbnailView view = new PhotoViewerThumbnailView(body);
        view.setSlideStateListener(mSlideStateListener);
        body.setTag(view);
        
        PhotoItem photoItem = (PhotoItem)mPhotoList.get(position);
        Bitmap bitmap = Utils.getThumnailImg(mContext.getContentResolver(), photoItem);
        view.getImageView().setImageBitmap(bitmap);
        
		((CustomViewPager) container).addView(body, 0);
		return body;
	}

	
	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
	    FrameLayout layout = (FrameLayout) object;
        PhotoViewerBodyInterface body = (PhotoViewerBodyInterface) layout
                .getTag();
        if (body != null) {
            String path = body.getImagePath();
            body.destroyItem();
            body = null;
        }
        ((CustomViewPager) container).removeView(layout);
	}

	@Override
	public void finishUpdate(ViewGroup container) {
		// TODO Auto-generated method stub
		super.finishUpdate(container);
	}

	@Override
	public void restoreState(Parcelable arg0, ClassLoader arg1) {
	}

	@Override
	public Parcelable saveState() {
		return null;
	}

	@Override
	public void startUpdate(ViewGroup arg0) {
		
	}

	@Override
	public void setPrimaryItem(ViewGroup container, int position, Object object) {
		// TODO Auto-generated method stub
		
		if (mPrimaryListener != null) {
			mPrimaryListener.createdPrimaryItem(position);
		}
		
		mCurrentPosition = position;

		mPager = (PhotoViewerPager) container;
		mBody = ((FrameLayout) object);
		if (mBody != null) {
            mBodyInterface = (PhotoViewerBodyInterface) mBody.getTag();
        }

		super.setPrimaryItem(container, position, object);
	}

	@Override
	public void notifyDataSetChanged() {
		// TODO Auto-generated method stub
		super.notifyDataSetChanged();
	}

	public void notifyDataSetChanged(boolean unchanged) {
		// TODO Auto-generated method stub
		if (!unchanged) {
			super.notifyDataSetChanged();
		} else {
			super.notifyDataSetChanged();
		}
	}

	@Override
	public int getItemPosition(Object object) {
		// return super.getItemPosition(object);
		return POSITION_NONE;
	}
	
	public void setPrimaryItemListener(AdapterPrimaryItemListener listener) {
		mPrimaryListener = listener;
	}

	/**
	 * Zoom모드를 설정하도록 한다.
	 * @param enable true-zoom진입, false-zoom빠져나오기
	 * @param zoom zoom모드 min_zoom(-1) 최소, normal(0) 핀치줌, max_zoom(1) 최대줌, double_tap(2) 더블탭줌
	 * @param point double_tap이라면 tap한 위치정보를 전달해준다. 아니라면 (0,0)
	 */
	public void setZoomMode(boolean enable, int zoom, Point point) {
	    if (mBodyInterface != null)
            mBodyInterface.setZoomMode(enable, zoom, point);
	}

	/**
	 * 현재 Zoom상태인지 가져온다.
	 * @return boolean
	 */
	public boolean isZoomMode() {
	    if (mBodyInterface != null) {
            return mBodyInterface.isZoomMode();
        } else {
            return false;
        }
	}

	/**
	 * 현재 Tap으로 최대Zoom상태인지 확인한다.<br>
	 * TapZoom은 2단계로 줌한다. <br> 
	 * TapZooming 1st 1.7배<br>
	 * TapZooming 2nd 3배<br>
	 * 
	 * @return boolean
	 */
	public boolean isMaxDoubleTapZoom() {
	    if (mBodyInterface != null) {
            return mBodyInterface.isMaxDoubleTapZoom();
        } else {
            return false;
        }
	}

	
	/**
	 * 현재 보이고 있는 body의 layout을 가져온다.
	 * @return FrameLayout
	 */
	public FrameLayout getBodyLayout() {
		return mBody;
	}

	/**
	 * dataset들을 전달받는다.
	 * @param totalcount
	 * @param list
	 */
	public void setPhotoList(int totalcount, ArrayList<PhotoItem> list) {
		mPhotoTotalCount = totalcount;
		mPhotoList = list;
		notifyDataSetChanged();
	}

	/**
     * 현재 Slide상태를 전달받을 Listener를 각 바디에 등록한다. 
     * @param listener
     */
    public void setSlideStateListener(SlideStateListener listener) {
        mSlideStateListener = listener;
        if (mBodyInterface != null) {
            mBodyInterface.setSlideStateListener(mSlideStateListener);
        }
    }
    
	/**
	 * 보여줄 이미지의 totalCount를 전달해준다.
	 * @param totalcount
	 */
	public void setTotalCount(int totalcount) {
		mPhotoTotalCount = totalcount;
		notifyDataSetChanged();
	}

	/**
	 * Adapter초기화 처리
	 */
	public void clear() {
		mInflater = null;
		if (mPhotoList != null && !mPhotoList.isEmpty()) {
			mPhotoList.clear();
		}
		mPhotoList = null;
	}

	/**
     * Body를 control할 수 있는 interface를 가져온다.
     * @return PhotoViewerBodyInterface
     */
    public PhotoViewerBodyInterface getBodyInterface() {
        return mBodyInterface;
    }
    
}
